<?php

namespace plugins\message_board\controller; 

use cmf\controller\PluginAdminBaseController;

class AdminIndexController extends PluginAdminBaseController
{

	/**
	 * 任务管理模块 菜单注解
	 * @adminMenu(
	 * 		'name'		=>	'留言板管理',
	 * 		'parent'	=>	'admin/Plugin/default',
	 * 		'display'	=>	true,
	 * 		'hasView'	=>	true,
	 * 		'order'		=>	9999,
	 * 		'icon'		=>	'',
	 * 		'remark'	=>	'留言板管理',
	 * 		'param'		=>	''
	 * )
	 */
	public function index()
	{
		return $this->fetch();	
	}

	//获取留言列表
	public function getList()
	{
		$data = $this->request->post();

		$page = empty($data['page']) ? 1 : $data['page'];
		$pagesize = empty($data['pagesize']) ? 10 : $data['pagesize'];

		$where = [];	//搜索条件
		//用户名搜索条件判断
		if(!empty($data['user_name'])){
			$where['b.user_login'] = ['like','%'.$data['user_name'].'%'];
		}
		//标题搜索条件判断
		if(!empty($data['title'])){
			$where['a.title'] = ['like','%'.$data['title'].'%'];
		}

		//创建时间搜索条件判断
		if(!empty($data['create_time'])){
			$where['a.create_time'] = ['between time',$data['create_time']];
		}

		$order = [];	//排序
		$order['id'] = 'desc';	//id倒序

		$field = [];	//获取字段
		$field[] = 'a.*';	//获取全部的字段
		$field[] = 'b.user_login';	//获取部分的字段

		//查询所需数据
		$list = db('message_board')
				->alias('a')
				->join("user b",'a.uid = b.id','left')
				->where($where)
				->order($order)
				->field($field)
				->paginates($pagesize,false,['page'=>$page])
				->each(function($item){
					//数据转换
					$item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
					return $item;
				});

		return api_json_echo(true,'',$list);
	}

	//新建留言
	public function addMessage()
	{
		$data = $this->request->post();

		//内容检测
		if(empty($data['title'])){
			return api_json_echo(false,'请输入标题');
		}

		//加入自动生成的参数
		$data['uid'] = cmf_get_current_admin_id();
		$data['create_time'] = time();

		$res = db('message_board')->insert($data);

		if($res){
			return api_json_echo(true,'新建成功');
		}
		return api_json_echo(false,'新建失败请重试');
	}

	//留言详情
	public function detailMessage()
	{
		$data = $this->request->post();

		$field = [];
		$field[] = 'a.*';
		$field[] = 'b.user_login';

		$info = db('message_board')
				->alias('a')
				->join("user b",'a.uid = b.id',"left")
				->field($field)
				->where(['a.id'=>$data['id']])
				->find();

		//日期时间戳转换
		$info['create_time'] = date('Y-m-d H:i:s',$info['create_time']);

		return api_json_echo(true,'',$info);
	}

	//删除留言
	public function delMessage()
	{
		$data = $this->request->post();

		//检测传参
		if(empty($data['id'])){
			return api_json_echo(false,'请选择相应的留言');
		}

		//支持单个或数组传入数据
		$res = db('message_board')->where(['id'=>['in',$data['id']]])->delete();

		if($res){
			return api_json_echo(true,'删除成功');
		}
		return api_json_echo(false,'删除失败请重试');
	}

	//空的演示页面
	public function black()
	{
		return $this->fetch();
	}

}